# -*- coding: utf-8 -*-
"""
角色管理控制层

负责处理角色、权限、销售员客户关系等相关的HTTP请求和响应
"""
from fastapi import APIRouter, HTTPException, Depends, Query
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
from app.services.role_service import (
    RoleService, SalesmanService, CustomerService, OrderService, PermissionMiddleware
)
from app.controllers.user_controller import get_current_user

# 创建路由
role_router = APIRouter(
    prefix="/role",
    tags=["role"],
    responses={404: {"description": "Not found"}}
)

salesman_router = APIRouter(
    prefix="/salesman",
    tags=["salesman"],
    responses={404: {"description": "Not found"}}
)

customer_router = APIRouter(
    prefix="/customer",
    tags=["customer"],
    responses={404: {"description": "Not found"}}
)

order_router = APIRouter(
    prefix="/order",
    tags=["order"],
    responses={404: {"description": "Not found"}}
)

# HTTP Bearer token scheme
security = HTTPBearer()

# 初始化服务层
role_service = RoleService()
salesman_service = SalesmanService()
customer_service = CustomerService()
order_service = OrderService()
permission_middleware = PermissionMiddleware()

# Pydantic 模型
class RoleSwitchRequest(BaseModel):
    user_id: str = Field(..., description="用户ID")
    new_role: str = Field(..., description="新角色", pattern="^(customer|salesman|admin)$")

class CustomerCreateRequest(BaseModel):
    nickname: str = Field(..., description="客户昵称")
    phone: Optional[str] = Field(None, description="手机号")
    email: Optional[str] = Field(None, description="邮箱")
    avatar: Optional[str] = Field("", description="头像URL")

class CustomerSwitchRequest(BaseModel):
    customer_id: str = Field(..., description="客户ID")

class ProxyOrderRequest(BaseModel):
    customer_id: str = Field(..., description="客户ID")
    total_amount: float = Field(..., description="订单总金额")
    discount_amount: Optional[float] = Field(0, description="优惠金额")
    shipping_fee: Optional[float] = Field(0, description="运费")
    final_amount: float = Field(..., description="最终金额")
    payment_method: Optional[str] = Field(None, description="支付方式")
    shipping_address: Optional[str] = Field(None, description="收货地址")
    notes: Optional[str] = Field(None, description="订单备注")

class PagePermissionRequest(BaseModel):
    page_path: str = Field(..., description="页面路径")


# =========================== 角色权限相关接口 ===========================

@role_router.get("/permissions")
async def get_user_permissions(current_user = Depends(get_current_user)):
    """获取当前用户权限信息"""
    try:
        user_id = current_user.get('user_id')
        permissions = role_service.get_user_permissions(user_id)
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": permissions
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取权限信息失败: {str(e)}")


@role_router.post("/switch")
async def switch_role(request: RoleSwitchRequest, current_user = Depends(get_current_user)):
    """用户角色切换"""
    try:
        current_user_id = current_user.get('user_id')
        result = role_service.switch_role(request.user_id, request.new_role, current_user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"角色切换失败: {str(e)}")


@role_router.post("/check-page")
async def check_page_permission(request: PagePermissionRequest, current_user = Depends(get_current_user)):
    """检查页面访问权限"""
    try:
        user_id = current_user.get('user_id')
        result = permission_middleware.check_page_permission(user_id, request.page_path)
        
        return {
            "code": 200,
            "message": "检查完成",
            "data": result
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"权限检查失败: {str(e)}")


@role_router.get("/navigation")
async def get_navigation_menu(current_user = Depends(get_current_user)):
    """获取用户导航菜单"""
    try:
        user_id = current_user.get('user_id')
        menu = permission_middleware.get_navigation_menu(user_id)
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": {"menu": menu}
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取导航菜单失败: {str(e)}")


# =========================== 销售员功能接口 ===========================

@salesman_router.get("/dashboard")
async def get_salesman_dashboard(current_user = Depends(get_current_user)):
    """获取销售员仪表板"""
    try:
        salesman_id = current_user.get('user_id')
        dashboard_data = salesman_service.get_salesman_dashboard(salesman_id)
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": dashboard_data
        }
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取仪表板数据失败: {str(e)}")


@salesman_router.get("/customers")
async def get_customer_list(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    current_user = Depends(get_current_user)
):
    """获取销售员的客户列表"""
    try:
        salesman_id = current_user.get('user_id')
        customers = salesman_service.get_customer_list(salesman_id, page, page_size)
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": customers
        }
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取客户列表失败: {str(e)}")


@salesman_router.post("/customers")
async def add_customer(request: CustomerCreateRequest, current_user = Depends(get_current_user)):
    """销售员添加新客户"""
    try:
        salesman_id = current_user.get('user_id')
        customer_data = request.dict()
        result = salesman_service.add_customer(salesman_id, customer_data)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"添加客户失败: {str(e)}")


@salesman_router.post("/switch-customer")
async def switch_current_customer(request: CustomerSwitchRequest, current_user = Depends(get_current_user)):
    """切换当前服务的客户"""
    try:
        salesman_id = current_user.get('user_id')
        result = salesman_service.switch_current_customer(salesman_id, request.customer_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"切换客户失败: {str(e)}")


@salesman_router.get("/statistics")
async def get_sales_statistics(
    start_date: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"),
    end_date: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"),
    current_user = Depends(get_current_user)
):
    """获取销售统计数据"""
    try:
        salesman_id = current_user.get('user_id')
        statistics = salesman_service.get_sales_statistics(salesman_id, start_date, end_date)
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": statistics
        }
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取销售统计失败: {str(e)}")


@salesman_router.get("/orders")
async def get_salesman_orders(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    current_user = Depends(get_current_user)
):
    """获取销售员相关的订单"""
    try:
        salesman_id = current_user.get('user_id')
        orders = order_service.get_salesman_orders(salesman_id, page, page_size)
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": orders
        }
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单列表失败: {str(e)}")


# =========================== 客户管理接口 ===========================

@customer_router.get("/{customer_id}/profile")
async def get_customer_profile(customer_id: str, current_user = Depends(get_current_user)):
    """获取客户资料"""
    try:
        current_user_id = current_user.get('user_id')
        profile = customer_service.get_customer_profile(customer_id, current_user_id)
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": profile
        }
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取客户资料失败: {str(e)}")


@customer_router.get("/search")
async def search_customers(
    keyword: str = Query(..., description="搜索关键词"),
    salesman_filter: bool = Query(True, description="是否只搜索自己的客户（销售员）"),
    current_user = Depends(get_current_user)
):
    """搜索客户"""
    try:
        current_user_id = current_user.get('user_id')
        customers = customer_service.search_customers(keyword, current_user_id, salesman_filter)
        
        return {
            "code": 200,
            "message": "搜索完成",
            "data": {"customers": customers}
        }
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"搜索客户失败: {str(e)}")


@customer_router.get("/{customer_id}/orders")
async def get_customer_orders(
    customer_id: str,
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    current_user = Depends(get_current_user)
):
    """获取客户订单"""
    try:
        current_user_id = current_user.get('user_id')
        orders = order_service.get_customer_orders(customer_id, current_user_id, page, page_size)
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": orders
        }
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取客户订单失败: {str(e)}")


# =========================== 订单管理接口 ===========================

@order_router.post("/proxy")
async def create_proxy_order(request: ProxyOrderRequest, current_user = Depends(get_current_user)):
    """销售员代理下单"""
    try:
        salesman_id = current_user.get('user_id')
        order_data = request.dict()
        result = order_service.create_proxy_order(salesman_id, order_data)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"代理下单失败: {str(e)}")


# =========================== 扩展用户控制器 ===========================

# 扩展现有的用户控制器，添加角色相关功能
def extend_user_controller():
    """扩展用户控制器，添加角色相关的用户信息"""
    from app.controllers.user_controller import router as user_router
    
    @user_router.get("/profile-extended")
    async def get_user_profile_extended(current_user = Depends(get_current_user)):
        """获取扩展的用户资料（包含角色信息）"""
        try:
            user_id = current_user.get('user_id')
            
            # 获取基本用户信息
            from app.services.user_service import UserService
            user_service = UserService()
            user = user_service.verify_token(current_user.get('access_token', ''))
            
            if not user:
                raise HTTPException(status_code=401, detail="用户信息获取失败")
            
            # 获取权限信息
            permissions = role_service.get_user_permissions(user_id)
            
            # 获取导航菜单
            navigation = permission_middleware.get_navigation_menu(user_id)
            
            return {
                "code": 200,
                "message": "获取成功",
                "data": {
                    "user_info": {
                        "user_id": user.get('user_id'),
                        "user_no": user.get('user_no'),
                        "nickname": user.get('nickname'),
                        "avatar": user.get('avatar'),
                        "phone": user.get('phone'),
                        "email": user.get('email'),
                        "wechat_nickname": user.get('wechat_nickname'),
                        "wechat_avatar": user.get('wechat_avatar'),
                        "gender": user.get('gender'),
                        "birthday": user.get('birthday'),
                        "user_role": user.get('user_role'),
                        "salesman_no": user.get('salesman_no'),
                        "department": user.get('department'),
                        "salesman_level": user.get('salesman_level'),
                        "last_login_time": user.get('last_login_time'),
                        "created_time": user.get('created_time')
                    },
                    "permissions": permissions,
                    "navigation": navigation
                }
            }
        except HTTPException:
            raise
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"获取用户资料失败: {str(e)}")

# 执行扩展
extend_user_controller() 